package com.hknc.btscale;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;

/**
 * desc:
 * date:2021/10/19 10:08
 * author:sunguiyong
 */
public class AutoScrollRecyclerView extends RecyclerView {
    private static final long TIME_AUTO_POLL = 100;
    AutoPollTask autoPollTask;
    private boolean running; //标示是否正在自动轮询
    private boolean canRun;//标示是否可以自动轮询,可在不需要的是否置false
    private int mMax;

    public AutoScrollRecyclerView(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attrs) {
        super(context, attrs);
        autoPollTask=new AutoPollTask(this);
    }
    static class AutoPollTask implements Runnable{
        private final WeakReference<AutoScrollRecyclerView> mReference;

        public AutoPollTask(AutoScrollRecyclerView reference) {
            mReference = new WeakReference<AutoScrollRecyclerView>(reference);
        }

        @Override
        public void run() {
//            AutoScrollRecyclerView recyclerView=mReference.get();
//            if (recyclerView != null && recyclerView.running && recyclerView.canRun) {
//                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                int lastVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
//                if (lastVisibleItemPosition == recyclerView.mMax-1)//如果真有人等到一直滚动到最大值那就让他回到头部重新滚
//                    recyclerView.scrollToPosition(0);
//                recyclerView.scrollBy(2, 2);
//                recyclerView.postDelayed(recyclerView.autoPollTask, recyclerView.TIME_AUTO_POLL);
//            }

            AutoScrollRecyclerView recyclerView = mReference.get();
            if (recyclerView != null && recyclerView.running && recyclerView.canRun) {
                recyclerView.scrollBy(2, 2);
                recyclerView.postDelayed(recyclerView.autoPollTask, TIME_AUTO_POLL);
            }
        }
    }
    public void start(int max){
        if (running)
            stop();
        canRun = true;
        running = true;
        postDelayed(autoPollTask, TIME_AUTO_POLL);
    }

    private void stop() {
        running=false;
        removeCallbacks(autoPollTask);
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return false;
    }
}
